import os
import asyncio
from telethon import TelegramClient
from tqdm import tqdm

# ======================
# YOUR CREDENTIALS
# ======================
api_id = 1234567  # <-- paste your api_id (number)
api_hash = "YOUR_API_HASH_HERE"  # <-- paste your api_hash

channel_username = "CHANNEL_USERNAME"  
# Example:
# "somechannel"
# or "https://t.me/somechannel"

download_dir = "downloaded_channel"

os.makedirs(download_dir, exist_ok=True)

client = TelegramClient("session", api_id, api_hash)


async def main():
    await client.start()

    print("Connecting to channel...")
    entity = await client.get_entity(channel_username)

    messages = []

    async for msg in client.iter_messages(entity, limit=None):
        messages.append(msg)

    print(f"Total messages found: {len(messages)}")

    media_path = os.path.join(download_dir, "media")

    for msg in tqdm(messages):
        if msg.media:
            try:
                await client.download_media(msg, file=media_path)
            except Exception as e:
                print("Error:", e)

    # Save text messages
    with open(os.path.join(download_dir, "messages.txt"), "w", encoding="utf-8") as f:
        for msg in messages:
            if msg.message:
                f.write(f"{msg.date} - {msg.message}\n")

    print("DONE ✅ All data downloaded!")


with client:
    client.loop.run_until_complete(main())
